//
//  ChooseTribeViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/1/13.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "ChooseTribeViewController.h"
#import "ZYTagSignView.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "ChooseTribeViewController.h"
#import "Object2Json.h"
#import "BaseTabBarControllerConfig.h"
#import "IndexNewViewController.h"

static const NSInteger kButtonTag = 9000;

@interface ChooseTribeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableDictionary *tribeDic;
@property (nonatomic,retain) NSMutableArray *tribeArr;
@property (nonatomic,retain) NSMutableArray *tribeSelectArr;
@property (nonatomic,retain) NSString *bannerImgUrl;
@property (nonatomic, strong) NSMutableArray *idarray;

@end

@implementation ChooseTribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //隐藏系统导航
    self.navigationController.navigationBarHidden = YES;
    _tribeDic= [NSMutableDictionary new];
    _tribeArr = [NSMutableArray new];
    _tribeSelectArr = [[NSMutableArray alloc]init];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUI];
    //数据请求
    [self request];
}
- (void)setUI
{
    self.view.backgroundColor = [UIColor colorWithRed:32/255.0 green:32/255.0 blue:32/255.0 alpha:1.0f];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -21,ScreenW , ScreenH+21-130*kScale) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    [self.view addSubview:_mainTableView];
    CGFloat nextBtnH = 130*kScale;
    ZYButton *nextBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(0, ScreenH-nextBtnH, ScreenW, nextBtnH);
    nextBtn.backgroundColor = [UIColor blackColor];
    [nextBtn setTitle:@"选好了,开启艺术生活" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
}

- (void)request
{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/sys/index/getIndexTribe",APIYIGOU];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //NSDictionary *parameters = @{@"label_names" : @[@"123"]};
    //NSString *jsonStr = [self DataTOjsonString:@[@"123"]];
    //NSLog(@"jsonStr:%@",jsonStr);
    
    [manager POST:urlStr parameters:_tagSelectArr success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100)
        {
            _tribeArr = dict[@"data"];
            DYLog(@"qql===dict:%@", dict);
            DYLog(@"qql===dict:%ld",_tribeArr.count);
            
            [_mainTableView reloadData];
        }
        else
        {
            
        }
        DYLog(@"result:%@", dict.description);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
    }];
    
    
    NSString *urlStr2 = [NSString stringWithFormat:@"%@/sys/index/indexImg?type=01-2",APIYIGOU]
    ;
    
    DYBaseRequest *request2 = [DYBaseRequest new];
    request2.requestUrl = urlStr2;
    [request2 dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"2222222%@",allDic);
        NSArray *dataArr = allDic[@"data"];
        if (dataArr.count>0) {
            _bannerImgUrl = allDic[@"data"][0][@"ad_img_url"];
        }
        
        [_mainTableView reloadData];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //    if (section==0) {
    //        return 1;
    //    }
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell不能点击
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0)
    {
        UIImageView *bannerImg = [[UIImageView alloc]init];
        bannerImg.frame = CGRectMake(0, 0, ScreenW, 418*kScale);
        NSString *imgurl = [NSString stringWithFormat:@"%@?imageView2/0/w/%d/h/%d", _bannerImgUrl, (int)ScreenW, 0];
        [bannerImg sd_setImageWithURL:[NSURL URLWithString:imgurl]];
        [cell addSubview:bannerImg];
        ZYButton *addBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
        [addBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
        addBtn.frame = CGRectMake(30*kScale, 30*kScale, 60*kScale, 60*kScale);
        [addBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:addBtn];
    }
    else if (indexPath.section==1)
    {
        
        for (int i = 0; i < _tribeArr.count;i++)
        {
            
            CGFloat leftSpace = 30*kScale;
            CGFloat line = i/3;
            CGFloat colum = i%3;
            CGFloat imageViewW = 204*kScale;
            CGFloat titleLableH = 42;
            CGFloat introducLableH = 30;
            CGFloat addBtnW = 108*kScale;
            CGFloat addBtnH = 44*kScale;
            CGFloat publicSpaceW = (ScreenW-2*leftSpace-3*imageViewW)/2;
            CGFloat publicSpaceH = 30*kScale;
            CGFloat tribeH = imageViewW+titleLableH+introducLableH+addBtnH+publicSpaceH+20*kScale+16*kScale*2;
            
            UIImageView *imageView = [[UIImageView alloc]init];
            NSLog(@"%@",_tribeArr[i][@"tribe_bg_img"]);
            if ([_tribeArr[i][@"tribe_bg_img"] isEqualToString:@""]) {
                
            }
            else
            {
                [imageView sd_setImageWithURL:[NSURL URLWithString:_tribeArr[i][@"tribe_bg_img"]]] ;
            }
            
            
            imageView.frame = CGRectMake(leftSpace+(publicSpaceW+imageViewW)*colum, 70*kScale+tribeH*line, imageViewW, imageViewW);
            [cell addSubview:imageView];
            UILabel *titleLable = [[UILabel alloc]init];
            titleLable.frame = CGRectMake(leftSpace+(publicSpaceW+imageViewW)*colum, 70*kScale+tribeH*line+20*kScale+imageViewW, imageViewW, titleLableH);
            titleLable.text = _tribeArr[i][@"tribe_name"];
            titleLable.font = [UIFont systemFontOfSize:17];
            titleLable.textAlignment = NSTextAlignmentCenter;
            titleLable.numberOfLines = 2;
            [cell addSubview:titleLable];
            
            UILabel *introLable = [[UILabel alloc]init];
            introLable.frame = CGRectMake(leftSpace+(publicSpaceW+imageViewW)*colum, 70*kScale+tribeH*line+20*kScale+imageViewW+16*kScale+titleLableH, imageViewW, introducLableH);
            introLable.text = _tribeArr[i][@"tribe_desc"];
            introLable.font = [UIFont systemFontOfSize:12];
            introLable.numberOfLines = 2;
            [cell addSubview:introLable];
            ZYButton *addBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
            addBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            [addBtn setTitle:@"加入" forState:UIControlStateNormal];
            [addBtn setTitle:@"已加入" forState:UIControlStateSelected];
            addBtn.backgroundColor = ZallColorFromRGB(0x1fa2b6);
            addBtn.frame = CGRectMake(leftSpace+(publicSpaceW+imageViewW)*colum+(imageViewW-addBtnW)/2, 70*kScale+tribeH*line+20*kScale+imageViewW+16*kScale+titleLableH+16*kScale+introducLableH, addBtnW, addBtnH);
            [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            //addBtn.tag = [_tribeArr[i][@"tribe_id"]integerValue];
            addBtn.tag = kButtonTag + i;
            [self.idarray addObject:_tribeArr[i][@"tribe_id"]];
            addBtn.tagTitle = titleLable.text;
            [cell addSubview:addBtn];
        }
        
    }
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(cancleSelect) withObject:nil afterDelay:0.1f];
    
    
}
- (void)cancleSelect
{
    [_mainTableView deselectRowAtIndexPath:[_mainTableView indexPathForSelectedRow] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 418*kScale;
    }
    CGFloat line = (_tribeArr.count+2)/3;
    CGFloat imageViewW = 204*kScale;
    CGFloat titleLableH = 42;
    CGFloat introducLableH = 30;
    CGFloat addBtnH = 44*kScale;
    CGFloat publicSpaceH = 30*kScale;
    CGFloat tribeH = imageViewW+titleLableH+introducLableH+addBtnH+publicSpaceH+20*kScale+16*kScale*2;
    return  70*kScale+tribeH*line;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
//修改状态栏字体
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
//点击加号按钮
- (void)addBtnClick:(ZYButton*)sender
{
    if (sender.selected==NO) {
        sender.backgroundColor = ZallColorFromRGB(0xe7e7e7);
        sender.selected=YES;
        NSInteger index = sender.tag - kButtonTag;
        NSString *tid = self.idarray[index];
        [_tribeDic setObject:tid forKey:sender.tagTitle];
        NSLog(@"111111%@",_tribeDic);
    }
    else
    {
        sender.selected=NO;
        sender.backgroundColor = ZallColorFromRGB(0x1fa2b6);
        
        [_tribeDic removeObjectForKey:sender.tagTitle];
        //        NSLog(@"22222%@",_tagDic);
    }
    
}
//点击下一步
- (void)nextClick
{
    
    [_tribeSelectArr addObjectsFromArray:_tribeDic.allValues];
    if (_tribeSelectArr.count==0)
    {
        [ViewFactory showInfoMsg:@"请选择部落"];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"udisjointribe"];
        NSLog(@"666666%ld,%@",_tribeSelectArr.count,_tribeSelectArr);
        NSString *urlStr = [NSString stringWithFormat:@"%@/hytribe/batchJoinTribe",APIYIGOU];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //NSDictionary *parameters = @{@"label_names" : @[@"123"]};
        //NSString *jsonStr = [self DataTOjsonString:@[@"123"]];
        //NSLog(@"jsonStr:%@",jsonStr);
        
        [manager POST:urlStr parameters:_tribeSelectArr success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            if ([[dict valueForKey:@"code"] intValue] == 100)
            {
                _tribeArr = dict[@"data"];
                DYLog(@"qql===dict:%@", dict);
                self.navigationController.navigationBarHidden = NO;
                for (UIViewController *temp in self.navigationController.viewControllers) {
                    if ([temp isKindOfClass:[IndexNewViewController class]]) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:POST_LOGINSUC object:nil];
                        [self.navigationController popToViewController:temp animated:YES];
                    }
                } ;
                [ViewFactory showSuccess:@"添加成功"];
            } else
            {
                [ViewFactory showInfoMsg:@"添加失败"];
                [_tribeSelectArr removeAllObjects];
            }
            DYLog(@"result:%@", dict.description);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error %ld",(long)error.code);
        }];
        NSString *strArr = @"";
        for (int i = 0; i<_tribeSelectArr.count; i++)
        {
            strArr = [NSString stringWithFormat:@"%@,%@",strArr,_tribeSelectArr[i]];
        }
        strArr =   [strArr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        DYLog(@"strArr===%@",strArr);
        
        
        
    }
}

ARRAY_INIT(idarray)
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
